package com.aaa.medicine.service.impl;

import com.aaa.entity.CareOrderItem;
import com.aaa.entity.Medicines;
import com.aaa.medicine.dao.CareOrderItemDao;
import com.aaa.medicine.dao.MedicinesMapper;
import com.aaa.medicine.service.IMedicinesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class MedicinesServiceImpl extends ServiceImpl<MedicinesMapper, Medicines> implements IMedicinesService {

    @Autowired
    private MedicinesMapper medicinesMapper;
    @Resource
    private CareOrderItemDao careOrderItemDao;

    @Override
    public IPage<Medicines> getAll(Page page, String medicinesName, String keywords, String status, String medicinesType, String prescriptionType, String producterId) {
        return medicinesMapper.getAdd(page,medicinesName,keywords,status,medicinesType,prescriptionType,producterId);
    }
    @Transactional
    @Override
    public Boolean selectList(String itemId) {
        QueryWrapper<CareOrderItem> wrapper=new QueryWrapper<>();
        wrapper.eq("item_id",itemId);
        wrapper.eq("item_type",0);
        List<CareOrderItem> careOrderItems = careOrderItemDao.selectList(wrapper);
        for (CareOrderItem careOrderItem : careOrderItems) {
            double num = Double.parseDouble(careOrderItem.getNum().toString());
            String itemName = careOrderItem.getItemName();

            QueryWrapper<Medicines> wrapper1=new QueryWrapper<>();
            wrapper1.eq("medicines_name",itemName);
            Medicines medicines = medicinesMapper.selectOne(wrapper1);

            double medicinesStockNum =Double.parseDouble(medicines.getMedicinesStockNum().toString());
            double a=medicinesStockNum- num;
            if(a>=0){
                BigDecimal i= BigDecimal.valueOf(medicinesStockNum- num);
                Medicines medicines1=new Medicines();
                medicines1.setMedicinesStockNum(i);
                QueryWrapper<Medicines> wrapper2=new QueryWrapper<>();
                wrapper2.eq("medicines_name",itemName);
                int update = medicinesMapper.update(medicines1, wrapper2);
                return update>0?true:false;
            }
        }
        return false;
    }

}
